package com.easytouch.vmhdl.fragment;

import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.easytouch.core.Configure;
import com.easytouch.core.DriverThread;
import com.easytouch.core.model.ColumnModel;
import com.easytouch.core.model.GoodsModel;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.SDCardTools;
import com.easytouch.core.utils.Tools;
import com.easytouch.vmhdl.AppApplication;
import com.easytouch.vmhdl.R;
import com.easytouch.vmhdl.activity.MainActivity;
import com.easytouch.vmhdl.animation.AnimationUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;

/**
 * Created by gulin on 2017/11/30.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {

    private Log mLogger = new Log("HomeFragment.txt");

    // video
    private MediaPlayer mMediaPlayer;
    private String[] mVideoNames;
    private String mVideoPath;
    private int mCurrentVideoIndex;
    private SurfaceView mPlayer;
    //images
    private ViewFlipper mVfImages;

    //AnimationSet animationSet = new AnimationSet(true);
    //TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, 10);
    private TextView tv_price_1, tv_price_2, tv_price_3, tv_price_4, tv_price_5, tv_price_6;
    private ArrayList<GoodsModel> goodsList;
    private ImageView bottom_1;
    private ImageView goods_1;
    private ImageView light_image_1;
    private ImageView bottom_2;
    private ImageView goods_2;
    private ImageView light_image_2;
    private ImageView bottom_3;
    private ImageView goods_3;
    private ImageView light_image_3;
    private ImageView bottom_4;
    private ImageView goods_4;
    private ImageView light_image_4;
    private ImageView bottom_5;
    private ImageView goods_5;
    private ImageView light_image_5;
    private ImageView bottom_6;
    private ImageView goods_6;
    private ImageView light_image_6;

    private LinearLayout mLlGoodsList;
    private RelativeLayout rl_1;
    private RelativeLayout rl_2;
    private RelativeLayout rl_3;
    private RelativeLayout rl_4;
    private RelativeLayout rl_5;
    private RelativeLayout rl_6;

    private ImageView mIvMore;

    private TextView mTvMac;

    private MyHandler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        hideTop();
        hideBottom();

        mPlayer = view.findViewById(R.id.sv_player);
        mVfImages = view.findViewById(R.id.vf_display);

        tv_price_1 = view.findViewById(R.id.tv_price_1);
        tv_price_2 = view.findViewById(R.id.tv_price_2);
        tv_price_3 = view.findViewById(R.id.tv_price_3);
        tv_price_4 = view.findViewById(R.id.tv_price_4);
        tv_price_5 = view.findViewById(R.id.tv_price_5);
        tv_price_6 = view.findViewById(R.id.tv_price_6);

        bottom_1 = view.findViewById(R.id.bottom_1);
        goods_1 = view.findViewById(R.id.goods_1);
        light_image_1 = view.findViewById(R.id.light_image_1);
        //getGoodsCoolORHot(1, tv_price_1, bottom_1, light_image_1);

        bottom_2 = view.findViewById(R.id.bottom_2);
        goods_2 = view.findViewById(R.id.goods_2);
        light_image_2 = view.findViewById(R.id.light_image_2);
        //getGoodsCoolORHot(2, tv_price_2, bottom_2, light_image_2);

        bottom_3 = view.findViewById(R.id.bottom_3);
        goods_3 = view.findViewById(R.id.goods_3);
        light_image_3 = view.findViewById(R.id.light_image_3);
        //getGoodsCoolORHot(2, tv_price_3, bottom_3, light_image_3);

        bottom_4 = view.findViewById(R.id.bottom_4);
        goods_4 = view.findViewById(R.id.goods_4);
        light_image_4 = view.findViewById(R.id.light_image_4);
        //getGoodsCoolORHot(2, tv_price_4, bottom_4, light_image_4);

        bottom_5 = view.findViewById(R.id.bottom_5);
        goods_5 = view.findViewById(R.id.goods_5);
        light_image_5 = view.findViewById(R.id.light_image_5);
        //getGoodsCoolORHot(1, tv_price_5, bottom_5, light_image_5);

        bottom_6 = view.findViewById(R.id.bottom_6);
        goods_6 = view.findViewById(R.id.goods_6);
        light_image_6 = view.findViewById(R.id.light_image_6);
        //getGoodsCoolORHot(2, tv_price_6, bottom_6, light_image_6);

        AnimationUtils.setTranslateAnimation(tv_price_1);
        AnimationUtils.setTranslateAnimation(tv_price_2);
        AnimationUtils.setTranslateAnimation(tv_price_3);
        AnimationUtils.setTranslateAnimation(tv_price_4);
        AnimationUtils.setTranslateAnimation(tv_price_5);
        AnimationUtils.setTranslateAnimation(tv_price_6);

        rl_1 = view.findViewById(R.id.rl_1);
        rl_2 = view.findViewById(R.id.rl_2);
        rl_3 = view.findViewById(R.id.rl_3);
        rl_4 = view.findViewById(R.id.rl_4);
        rl_5 = view.findViewById(R.id.rl_5);
        rl_6 = view.findViewById(R.id.rl_6);
        if (rl_1 != null) {
            rl_1.setOnClickListener(this);
        }
        if (rl_2 != null) {
            rl_2.setOnClickListener(this);
        }
        if (rl_3 != null) {
            rl_3.setOnClickListener(this);
        }
        if (rl_4 != null) {
            rl_4.setOnClickListener(this);
        }
        if (rl_5 != null) {
            rl_5.setOnClickListener(this);
        }
        if (rl_6 != null) {
            rl_6.setOnClickListener(this);
        }
        rl_1.setVisibility(View.GONE);
        rl_2.setVisibility(View.GONE);
        rl_3.setVisibility(View.GONE);
        rl_4.setVisibility(View.GONE);
        rl_5.setVisibility(View.GONE);
        rl_6.setVisibility(View.GONE);

        mIvMore = view.findViewById(R.id.bt_more);
        mIvMore.setOnClickListener(this);
        Button btPick = view.findViewById(R.id.bt_pickup);
        btPick.setOnClickListener(this);

        mLlGoodsList = view.findViewById(R.id.ll_goods_list);
        mLlGoodsList.setVisibility(View.GONE);

        mTvMac = view.findViewById(R.id.tv_mac);

        String displayRate = Configure.getConfigData(Configure.MAIN_DISPLAY_RATE);
        if(displayRate == null || "".equals(displayRate) || "0".equals(displayRate))
        {
            initImages();
        }
        else
        {
            initVideo();
        }

        mHandler = new MyHandler(this);
        mHandler.sendEmptyMessage(0);
        mHandler.sendEmptyMessageDelayed(1, 300);
        return view;
    }

    private void startAnime()
    {
        if(mIvMore != null)
        {
            AnimationDrawable animationDrawable = (AnimationDrawable) mIvMore.getDrawable();
            animationDrawable.start();
        }
    }

    private void setMac()
    {
        String macString = getString(R.string.main_mac);
        mTvMac.setText(String.format(macString, Configure.getMacNo()));
    }

    private void setGoodsInfo()
    {
        rl_1.setVisibility(View.GONE);
        rl_2.setVisibility(View.GONE);
        rl_3.setVisibility(View.GONE);
        rl_4.setVisibility(View.GONE);
        rl_5.setVisibility(View.GONE);
        rl_6.setVisibility(View.GONE);

        String recommend = Configure.getConfigData(Configure.MAIN_RECOMMEND);
        if(recommend == null || "".equals(recommend))
        {
            return;
        }
        String[] recommendGoods = recommend.split(";");
        if(recommendGoods == null || recommendGoods.length < 1)
        {
            return;
        }
        for(String id : recommendGoods)
        {
            String json = DriverThread.getInstance().getRoadInfo(id);
            if(json == null || "".equals(json))
            {
                continue;
            }
            try
            {
                JSONObject obj = new JSONObject(json);
                GoodsModel model = GoodsModel.fromJson(obj);
                if(model.isGoodsHaveStock()) {
                    if (goodsList == null) {
                        goodsList = new ArrayList<>();
                    }
                    goodsList.add(model);
                }
            }catch (JSONException e) {
                //continue;
            }
        }

//        //get all goods
//        for(int i = 0;i < 5;i++) {
//            String json = DriverThread.getInstance().getGoodsByCategory(i + 1, false);
//            if(json == null || "".equals(json))
//            {
//                continue;
//            }
//            try {
//                JSONObject object = new JSONObject(json);
//                JSONArray data = object.getJSONArray("data");
//                if(data == null || data.length() == 0)
//                {
//                    continue;
//                }
//                for (int j = 0;j < data.length();j++) {
//                    JSONObject obj = data.getJSONObject(j);
//                    GoodsModel model = GoodsModel.fromJson(obj);
//                    if(goodsList == null)
//                    {
//                        goodsList = new ArrayList<>();
//                    }
//                    goodsList.add(model);
//                }
//            } catch (JSONException e) {
//                //continue;
//            }
//        }
        if(goodsList == null)
        {
            return;
        }
        if(goodsList.size() > 0)
        {
            setGoodsItem(0, tv_price_1, bottom_1, light_image_1, goods_1);
            rl_1.setVisibility(View.VISIBLE);
        }
        if(goodsList.size() > 1)
        {
            setGoodsItem(1, tv_price_2, bottom_2, light_image_2, goods_2);
            rl_2.setVisibility(View.VISIBLE);
        }
        if(goodsList.size() > 2)
        {
            setGoodsItem(2, tv_price_3, bottom_3, light_image_3, goods_3);
            rl_3.setVisibility(View.VISIBLE);
        }
        if(goodsList.size() > 3)
        {
            setGoodsItem(3, tv_price_4, bottom_4, light_image_4, goods_4);
            rl_4.setVisibility(View.VISIBLE);
        }
        if(goodsList.size() > 4)
        {
            setGoodsItem(4, tv_price_5, bottom_5, light_image_5, goods_5);
            rl_5.setVisibility(View.VISIBLE);
        }
        if(goodsList.size() > 5)
        {
            setGoodsItem(5, tv_price_6, bottom_6, light_image_6, goods_6);
            rl_6.setVisibility(View.VISIBLE);
        }
        mLlGoodsList.setVisibility(View.VISIBLE);
    }

    private void setGoodsItem(final int position, final TextView label, final ImageView bottom, final ImageView light_image, final ImageView image)
    {
        GoodsModel goods = goodsList.get(position);
        switch (goods.getTemperatureState())
        {
            case ColumnModel.TEMPERATURE_NORMAL:
                label.setShadowLayer(20f, 0, 0, R.color.cool_lable);
                bottom.setImageResource(R.drawable.main_bottom_normal);
                light_image.setImageResource(R.drawable.main_light_normal);
                break;
            case ColumnModel.TEMPERATURE_COLD:
                label.setShadowLayer(20f, 0, 0, R.color.cool_lable);
                bottom.setImageResource(R.drawable.main_bottom_normal);
                light_image.setImageResource(R.drawable.main_light_normal);
                break;
            case ColumnModel.TEMPERATURE_HEAT:
                label.setShadowLayer(20f, 0, 0, R.color.hot_lable);
                bottom.setImageResource(R.drawable.main_bottom_hot);
                light_image.setImageResource(R.drawable.main_light_hot);
                break;
        }
        //价格
        String price = Tools.priceFormat(String.valueOf(goods.getPrice()));
        price = String.format(getResources().getString(R.string.goods_price), price);
        label.setText(price);
        //商品图片
        setImage(image, String.valueOf(goods.getCode()) + "/0.png");
    }

    public void setImage(ImageView imageView, String imageName) {

        mImageLoader.displayImage("file://" + AppApplication.path + "/images/goods_image/" + imageName, imageView, options, mLoadingListener);
    }

    private void initImages()
    {
        mPlayer.setVisibility(View.GONE);
        mVfImages.setVisibility(View.VISIBLE);
        mVfImages.setAutoStart(true);
        mVfImages.setInAnimation(getActivity(), R.anim.slide_in_right);
        mVfImages.setOutAnimation(getActivity(), R.anim.slide_out_left);

        if (!SDCardTools.isSDCardIsReady())
            return;

        File imageFile = new File(AppApplication.path + "/images/main_image");
        if (!imageFile.exists())
            return;
        String imageInfo = Configure.getConfigData(Configure.MAIN_IMAGE_NAMES);
        if (imageInfo == null || "".equals(imageInfo))
            return;
        String[] images = imageInfo.split(";");
        int len = images.length;
        for (int i = 0; i < len; i++) {
            if (images[i] == null || "".equals(images[i].trim()))
                return;
            ImageView imageView = new ImageView(getActivity());
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            mVfImages.addView(imageView);
            mImageLoader.displayImage("file://" + imageFile.getAbsoluteFile() + "/" + images[i].trim(), imageView, options, mLoadingListener);
        }
        String flipperTime = Configure.getConfigData(Configure.MAIN_IMAGE_TIME);
        if (flipperTime == null || "".equals(flipperTime))
            flipperTime = "5";
        mVfImages.setFlipInterval(Integer.parseInt(flipperTime) * 1000);
        if (len <= 1) {
            mVfImages.setAutoStart(false);
            mVfImages.stopFlipping();
        }
    }

    private void initVideo()
    {
        mPlayer.setVisibility(View.VISIBLE);
        mVfImages.setVisibility(View.GONE);
        String video = Configure.getConfigData(Configure.MAIN_VIDEO_NAMES);
        if(video == null && "".equals(video))
        {
            mLogger.e("no video files");
            return;
        }
        mVideoNames = video.split(";");
        // 视频播放
        mMediaPlayer = new MediaPlayer();
        // mMediaPlayer.setOnPreparedListener(new MediaPreparedListener());
        mMediaPlayer.setOnCompletionListener(new MediaCompletionListener());
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        // mPlayer.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mPlayer.getHolder().addCallback(new SurfaceCallback());
        mMediaPlayer.setOnPreparedListener(new MediaPreparedListener());
        // 添加视频错误监听器
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if (mCurrentVideoIndex == mVideoNames.length - 1) {
                    mCurrentVideoIndex = 0;
                } else {
                    mCurrentVideoIndex++;
                }
                try {
                    if(mMediaPlayer != null)
                    {
                        mMediaPlayer.release();
                        mMediaPlayer = null;
                        initVideo();
                    }
                    play();
                } catch (Exception e) {
                    mLogger.e("mMediaPlayer.setOnErrorListener onError:" + e.toString());
                }

                return false;
            }
        });
        // 网上找的可以解决播放视频黑屏的问题
        getActivity().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        mPlayer.getHolder().setFormat(PixelFormat.TRANSPARENT);
    }

    public void play() throws IllegalArgumentException, SecurityException,
            IllegalStateException, IOException {

        File videoFile = null;

        for (int i = 1; i <= mVideoNames.length; i++) {

            if ("".equals(mVideoNames[mCurrentVideoIndex].trim())) {
                VideoIndexMoveNext();
                continue;
            }

            if (TextUtils.isEmpty(mVideoPath))
                videoFile = new File(AppApplication.path + "/video/"
                        + mVideoNames[mCurrentVideoIndex]);
            else
                videoFile = new File(AppApplication.ext_path + "/video/"
                        + mVideoNames[mCurrentVideoIndex]);
            if (videoFile.exists()) {
                break;
            }

            VideoIndexMoveNext();
        }

        if (videoFile == null)
            return;

        mMediaPlayer.reset();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        // mMediaPlayer.setDisplay(mPlayer.getHolder());
        mMediaPlayer.setDataSource(videoFile.getAbsolutePath());
        // mMediaPlayer.prepare();
        mMediaPlayer.prepareAsync();
    }

    public void VideoIndexMoveNext() {
        if (mCurrentVideoIndex == mVideoNames.length - 1) {
            mCurrentVideoIndex = 0;
        } else {
            mCurrentVideoIndex++;
        }
    }

    class SurfaceCallback implements SurfaceHolder.Callback {

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
            mPlayer.getHolder().setFixedSize(width, height);
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            if (mMediaPlayer == null)
                return;
            try {
                mMediaPlayer.setDisplay(holder); // 一旦surfaceDestroyed，就需要重新setDisplay(holder)
                // holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                play();
            } catch (IllegalStateException e) {
                mLogger.e("SurfaceCallback surfaceCreated:" + e.toString());
            } catch (IllegalArgumentException e) {
                mLogger.e("SurfaceCallback surfaceCreated:" + e.toString());
            } catch (SecurityException e) {
                mLogger.e("SurfaceCallback surfaceCreated:" + e.toString());
            } catch (IOException e) {
                mLogger.e("SurfaceCallback surfaceCreated:" + e.toString());
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                // mPosition = mMediaPlayer.getCurrentPosition();
                mMediaPlayer.stop();
            }
        }
    }

    class MediaCompletionListener implements MediaPlayer.OnCompletionListener {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if (mCurrentVideoIndex == mVideoNames.length - 1) {
                mCurrentVideoIndex = 0;
            } else {
                mCurrentVideoIndex++;
            }
            try {
                play();
            } catch (IOException e) {
                mLogger.e("MediaCompletionListener onCompletion:" + e.toString());
            }
        }
    }

    class MediaPreparedListener implements MediaPlayer.OnPreparedListener {

        @Override
        public void onPrepared(MediaPlayer mp) {
            mMediaPlayer.start();
            // if(mPosition != 0) mMediaPlayer.seekTo(mPosition);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch(id)
        {
            case R.id.bt_more:
                goToFragment(MainActivity.FRAGMENT_GOODS, null);
                break;
            case R.id.bt_pickup:
                MainActivity activity = (MainActivity)this.getActivity();
                if(activity != null)
                {
                    activity.showPick();
                }
                break;
            case R.id.rl_1:
                goToPay(0);
                break;
            case R.id.rl_2:
                goToPay(1);
                break;
            case R.id.rl_3:
                goToPay(2);
                break;
            case R.id.rl_4:
                goToPay(3);
                break;
            case R.id.rl_5:
                goToPay(4);
                break;
            case R.id.rl_6:
                goToPay(5);
                break;
        }
    }

    private void goToPay(final int position)
    {
        if(goodsList == null)
        {
            return;
        }
        if(position >= goodsList.size())
        {
            return;
        }
        GoodsModel goods = goodsList.get(position);
        Bundle bundle = new Bundle();
        bundle.putString(PayFragment.PARAM_GOODS, goods.toString());
        goToFragment(MainActivity.FRAGMENT_PAY, bundle);
    }

    @Override
    public void onDestroyView() {
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        if(mHandler != null)
        {
            mHandler.removeMessages(0);
        }
        super.onDestroyView();
    }

    static class MyHandler extends Handler
    {

        private SoftReference<HomeFragment> mFragment;

        public MyHandler(HomeFragment fragment)
        {
            mFragment = new SoftReference<HomeFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            if(mFragment == null || mFragment.get() == null)
            {
                return;
            }
            switch (msg.what)
            {
                case 0: //倒计时
                {
                    mFragment.get().setMac();
                    if(mFragment.get().goodsList == null)
                    {
                        mFragment.get().setGoodsInfo();
                    }
                    sendEmptyMessageDelayed(0, 1000);
                    break;
                }
                case 1:
                {
                    mFragment.get().startAnime();
                }
            }
        }
    }
}
